package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.zbkj.dal.base.enums.BizTypeEnum;
import com.zbkj.dal.entity.ba.BizImg;
import com.zbkj.dal.entity.ba.Discovery;
import com.zbkj.dal.pojo.request.PageParamRequest;
import com.zbkj.dal.pojo.request.ba.ConcludeDiscoveryRequest;
import com.zbkj.dal.pojo.request.ba.CreateDiscoveryRequest;
import com.zbkj.dal.pojo.request.ba.QueryDiscoveryRequest;
import com.zbkj.dal.pojo.response.ba.DiscoveryDetailResponse;
import com.zbkj.dal.pojo.response.ba.DiscoveryResponse;
import com.zbkj.dal.common.utils.SecurityUtil;
import com.zbkj.dal.dao.DiscoveryMapper;
import com.zbkj.service.service.*;
import com.zbkj.service.util.UserUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 全球找货 服务实现类
 * </p>
 *
 * @author jhui
 * @since 2023-10-03
 */
@Service
public class DiscoveryServiceImpl extends ServiceImpl<DiscoveryMapper, Discovery> implements DiscoveryService {
    @Autowired
    private UserService userService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private BizImgService bizImgService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Resource
    private AliSmsServiceImpl aliSmsService;

    @Override
    public List<DiscoveryResponse> listMyDiscovery(Integer status, PageParamRequest pageParamRequest) {
        List<DiscoveryResponse> discoveryResponses = Lists.newArrayList();
        Integer userId = userService.getUserIdException();
        LambdaQueryWrapper<Discovery> queryWrapper = Wrappers.lambdaQuery(Discovery.class);
        queryWrapper.eq(Discovery::getUid, userId);
        if (status != null && status != -1) {
            queryWrapper.eq(Discovery::getStatus, status);
        }
        queryWrapper.orderByDesc(Discovery::getId);
        queryWrapper.last("LIMIT " + (pageParamRequest.getPage() -1) * pageParamRequest.getLimit() + "," + pageParamRequest.getLimit());
        List<Discovery> list = list(queryWrapper);

        if (CollectionUtils.isEmpty(list)) {
            return discoveryResponses;
        }
        List<BizImg> bizImgs = Lists.newArrayList();
        List<Integer> ids = list.stream().map(m -> m.getId()).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(ids)) {
            bizImgs = bizImgService.listByBizIds(BizTypeEnum.DISCOVERY.getType(), ids);
        }
        for (Discovery discovery : list) {
            DiscoveryResponse discoveryResponse = new DiscoveryResponse();
            BeanUtils.copyProperties(discovery, discoveryResponse);
            List<String> paths = bizImgs.stream().filter(p -> ObjectUtils.nullSafeEquals(p.getBizId(), discovery.getId())
                            && StringUtils.isNotBlank(p.getPath())).map(m -> m.getPath())
                    .collect(Collectors.toList());
            discoveryResponse.setPics(paths);
            discoveryResponses.add(discoveryResponse);
        }

        return discoveryResponses;
    }

    @Override
    public Boolean deleteMyDiscovery(Integer id) {
        Integer userId = userService.getUserIdException();
        LambdaQueryWrapper<Discovery> queryWrapper = Wrappers.lambdaQuery(Discovery.class);
        queryWrapper.eq(Discovery::getId, id).eq(Discovery::getStatus, 0).eq(Discovery::getUid, userId);
        return this.remove(queryWrapper);
    }

    @Override
    public Boolean create(CreateDiscoveryRequest createDiscoveryRequest) {
        Integer userId = userService.getUserIdException();
        Discovery discovery = new Discovery();
        BeanUtils.copyProperties(createDiscoveryRequest, discovery);
        discovery.setUid(userId);
        discovery.setStatus(0);
        discovery.setCreateTime(LocalDateTime.now());
        discovery.setUpdateTime(LocalDateTime.now());

        //            bizImgService.deleteByBizId(BizTypeEnum.SHARE.getType(),)

        return Boolean.TRUE.equals(transactionTemplate.execute((e) -> {
//            bizImgService.deleteByBizId(BizTypeEnum.SHARE.getType(),)
            save(discovery);
            if (CollUtil.isNotEmpty(createDiscoveryRequest.getPics())) {
                createDiscoveryRequest.getPics().forEach(c -> {
                    c.setBizId(discovery.getId());
                    c.setCreateTime(LocalDateTime.now());
                    c.setUpdateTime(LocalDateTime.now());
                    c.setType(BizTypeEnum.DISCOVERY.getType());
                    c.setPath(systemAttachmentService.clearPrefix(c.getPath()));
                });

                bizImgService.saveBatch(createDiscoveryRequest.getPics());

                //发送短息
                aliSmsService.sendServiceMsg("全球找货");
            }
            return Boolean.TRUE;
        }));
    }

    @Override
    public DiscoveryDetailResponse detail(Integer id) {
        Discovery discovery = getById(id);
        DiscoveryDetailResponse discoveryResponse = new DiscoveryDetailResponse();
        BeanUtils.copyProperties(discovery, discoveryResponse);
        List<BizImg> bizImgs = bizImgService.listByBizId(BizTypeEnum.DISCOVERY.getType(), id);
        discoveryResponse.setPics(bizImgs);
        return discoveryResponse;
    }

    @Override
    public PageInfo<DiscoveryResponse> queryDiscovery(QueryDiscoveryRequest queryDiscoveryRequest, PageParamRequest pageParamRequest) {
        LambdaQueryWrapper<Discovery> queryWrapper = Wrappers.lambdaQuery(Discovery.class);
        if (queryDiscoveryRequest.getStatus() != null) {
            queryWrapper.eq(Discovery::getStatus, queryDiscoveryRequest.getStatus());
        }
        if (queryDiscoveryRequest.getBeginDate() != null) {
            queryWrapper.ge(Discovery::getCreateTime, queryDiscoveryRequest.getBeginDate());
        }
        if (queryDiscoveryRequest.getEndDate() != null) {
            queryWrapper.lt(Discovery::getCreateTime, queryDiscoveryRequest.getEndDate().plusDays(1));
        }
        queryWrapper.orderByDesc(Discovery::getId);
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<Discovery> list = this.list(queryWrapper);
        PageInfo<Discovery> pageInfo = PageInfo.of(list);
        PageInfo<DiscoveryResponse> result = new PageInfo<>();
        result.setTotal(pageInfo.getTotal());
        List<DiscoveryResponse> dtos = Lists.newArrayList();
        for (Discovery discovery : pageInfo.getList()) {
            DiscoveryResponse discoveryResponse = new DiscoveryResponse();
            BeanUtils.copyProperties(discovery, discoveryResponse);
            dtos.add(discoveryResponse);
        }
        result.setList(dtos);
        UserUtils.fillUsers(result.getList());

        if (CollectionUtils.isNotEmpty(dtos)) {
            List<Integer> adminIds = dtos.stream().filter(p -> p.getOperatorId() != null).distinct().map(m -> m.getOperatorId()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(adminIds)) {
                Map<Integer, String> nameMapByIdList = systemAdminService.getNameMapByIdList(adminIds);
                for (DiscoveryResponse discovery : result.getList()) {
                    if (discovery.getOperatorId() == null) {
                        continue;
                    }
                    discovery.setOperatorName(nameMapByIdList.get(discovery.getOperatorId()));
                }
            }
        }
        return result;
    }

    @Override
    public Boolean confirm(ConcludeDiscoveryRequest concludeDiscoveryRequest) {
        Integer id = SecurityUtil.getLoginUserVo().getUser().getId();
        concludeDiscoveryRequest.setOperatorId(id);
        LambdaUpdateWrapper<Discovery> updateWrapper = Wrappers.lambdaUpdate(Discovery.class);
        updateWrapper
                .set(Discovery::getCode, concludeDiscoveryRequest.getCode())
                .set(Discovery::getStatus, concludeDiscoveryRequest.getStatus())
                .set(Discovery::getRemark, concludeDiscoveryRequest.getRemark())
                .set(Discovery::getOperatorId, concludeDiscoveryRequest.getOperatorId())
                .set(Discovery::getUpdateTime, LocalDateTime.now())
                .set(Discovery::getServiceFee, concludeDiscoveryRequest.getServiceFee())
                .eq(Discovery::getId, concludeDiscoveryRequest.getId());
        return update(updateWrapper);
    }
}
